<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="tiny" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="文档" prop="documentId">
        <el-input
          v-model="queryParams.documentName"
          placeholder="请输入文档名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="接口编码" prop="interfaceCode">
        <el-input
          v-model="queryParams.interfaceCode"
          placeholder="请输入接口编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="中文名称" prop="interfaceCnName">
        <el-input
          v-model="queryParams.interfaceCnName"
          placeholder="请输入接口中文名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="接口类型" prop="interfaceType">
        <el-select v-model="queryParams.interfaceType" placeholder="请选择接口类型" clearable>
          <el-option
            v-for="dict in dict.type.submit_interface_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['submit:interface:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['submit:interface:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['submit:interface:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['submit:interface:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="interfaceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="接口ID" align="center" prop="interfaceId" /> -->
      <el-table-column label="文档名称" align="center" prop="documentName" />
      <el-table-column label="接口编码" align="center" prop="interfaceCode" />
      <el-table-column label="接口英文名称" align="center" prop="interfaceEnName" />
      <el-table-column label="接口类型" align="center" prop="interfaceType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.submit_interface_type" :value="scope.row.interfaceType"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['submit:interface:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['submit:interface:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改文档接口信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-divider content-position="center">接口基本信息</el-divider>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="文档" prop="documentId">
              <el-select v-model="form.documentId" placeholder="请选择文档">
                <el-option
                  v-for="document in this.documentList"
                  :key="document.documentId"
                  :label="document.documentName"
                  :value="document.documentId"
                ></el-option>
              </el-select>
          </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="接口编码" prop="interfaceCode">
              <el-input v-model="form.interfaceCode" placeholder="请输入接口编码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="中文名称" prop="interfaceCnName">
              <el-input v-model="form.interfaceCnName" placeholder="请输入接口中文名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="英文名称" prop="interfaceEnName">
              <el-input v-model="form.interfaceEnName" placeholder="请输入接口英文名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="接口描述" prop="interfaceDesc">
          <el-input v-model="form.interfaceDesc" placeholder="请输入接口描述" />
        </el-form-item>
        <el-form-item label="时间配置" prop="reportTimeConfig">
          <timeConfig 
          @timeConfigJsonChanged="handleTimeConfigJsonChange"
           :innerTimeConfig="form.reportTimeConfig">
          </timeConfig>
        </el-form-item>
        <el-divider content-position="center">接口文件信息</el-divider>
        <el-row>
          <el-col :span="12">
            <el-form-item label="接口类型" prop="interfaceType">
          <el-select v-model="form.interfaceType" placeholder="请选择接口类型">
            <el-option
              v-for="dict in dict.type.submit_interface_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="文件名称" prop="fileName">
              <el-input v-model="form.fileName" placeholder="请输入文件名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="文件编码" prop="encoding">
              <el-input v-model="form.encoding" placeholder="请输入文件编码格式" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="模板文件" prop="templateFileId">
              <file-upload v-model="form.fileStorageId"/>
            </el-form-item>
          </el-col> -->
        </el-row>
        <el-divider content-position="center">接口数据信息</el-divider>
        <!-- 数据采集方式 -->
        <el-form-item label="采集方式" prop="dataCollectType">
          <el-select v-model="form.dataCollectType" placeholder="请选择数据采集方式">
            <el-option label="同步采集" value="1"></el-option>
            <el-option label="手工填报" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item v-if="form.dataCollectType !== '2'" label="同步任务" prop="syncJobId">
              <el-select v-model="form.syncJobId" placeholder="请选择同步任务">
                <el-option
                  v-for="job in this.jobList"
                  :key="job.jobId"
                  :label="job.jobName"
                  :value="job.jobId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报送模型" prop="submitModelId">
              <el-select v-model="form.submitModelId" placeholder="请选择报送模型">
                <el-option
                  v-for="dataset in this.datasetList"
                  :key="dataset.datasetId"
                  :label="dataset.datasetName"
                  :value="dataset.datasetId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="center">接口字段信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddSubmitInterfaceField">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteSubmitInterfaceField">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-upload" size="mini" @click="handleImportSubmitInterfaceField">导入</el-button>
          </el-col>
        </el-row>
        <el-table :data="submitInterfaceFieldList" :row-class-name="rowSubmitInterfaceFieldIndex" @selection-change="handleSubmitInterfaceFieldSelectionChange" ref="submitInterfaceField">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="字段名称" prop="fieldCnName" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.fieldCnName" placeholder="请输入字段名称" />
            </template>
          </el-table-column>
          <el-table-column label="字段英文名称" prop="fieldEnName" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.fieldEnName" placeholder="请输入字段英文名称" />
            </template>
          </el-table-column>
          <el-table-column label="字段类型" prop="fieldType" width="150">
            <template slot-scope="scope">
              <el-select v-model="scope.row.fieldType" placeholder="请选择字段类型">
                <el-option
                  v-for="dict in dict.type.submit_field_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="字段长度" prop="fieldLength" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.fieldLength" placeholder="请输入字段长度" :disabled="disableFieldLength(scope.row.fieldType)" :required="isRequired(scope.row.fieldType)" />
            </template>
          </el-table-column>

          <el-table-column label="字段精度" prop="fieldPrecision" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.fieldPrecision" placeholder="请输入字段精度" :disabled="disableFieldPrecision(scope.row.fieldType)" :required="isRequired(scope.row.fieldType)" />
            </template>
          </el-table-column>
          <el-table-column label="是否必填" prop="isRequired" width="150">
            <template slot-scope="scope">
              <el-select v-model="scope.row.isRequired" placeholder="请选择是否必填">
                <el-option
                  v-for="dict in dict.type.submit_field_null_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="是否唯一" prop="isPrimary" width="150">
            <template slot-scope="scope">
              <el-select v-model="scope.row.isPrimary" placeholder="请选择是否唯一">
                <el-option
                  v-for="dict in dict.type.submit_field_unique_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="字段校验规则" prop="fieldCheck" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.fieldCheck" placeholder="请输入字段校验规则" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listInterface, getInterface, delInterface, addInterface, updateInterface } from "@/api/submit/interface";
import { listDocument } from "@/api/submit/document";
import { listDataset } from "@/api/data/dataset";
import { listJob } from "@/api/data/job";
import timeConfig from "./timeConfig.vue";

export default {
  components: { timeConfig: timeConfig },
  name: "Interface",
  dicts: ['submit_field_type', 'submit_interface_type', 'submit_field_null_type', 'submit_field_unique_type'],
  data() {
    return {
      // 传入的表达式
      expression: "",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedSubmitInterfaceField: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 文档接口信息表格数据
      interfaceList: [],
      // 接口字段表格数据
      submitInterfaceFieldList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        documentName: null,
        interfaceCode: null,
        interfaceCnName: null,
        interfaceType: null,
      },
      // 表单参数
      form: {},
      //存储文档列表
      documentList: [],
      //存储数据集列表
      datasetList: [],
      // 任务列表
      jobList: [],
      // 表单校验
      rules: {
        documentId: [
          { required: true, message: "文档不能为空", trigger: "blur" }
        ],
        interfaceCode: [
          { required: true, message: "接口编码不能为空", trigger: "blur" }
        ],
        interfaceEnName: [
          { required: true, message: "接口英文名不能为空", trigger: "blur" }
        ],
        interfaceType: [
          { required: true, message: "接口类型不能为空", trigger: "blur" }
        ],
        fileName: [
          { required: true, message: "文件名称不能为空", trigger: "blur" }
        ],
        reportTimeConfig: [
          { required: true, message: "时间配置不能为空", trigger: "blur" }
        ],
        syncJobId: [
          { required: true, message: "同步任务不能为空", trigger: "blur" }
        ],
        submitModelId: [
          { required: true, message: "报送模型不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询文档接口信息列表 */
    getList() {
      this.loading = true;
      listInterface(this.queryParams).then(response => {
        this.interfaceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        interfaceId: null,
        documentId: null,
        interfaceCode: null,
        interfaceCnName: null,
        interfaceEnName: null,
        interfaceType: null,
        fileName: null,
        reportTimeConfig: null,
        interfaceDesc: null,
        syncJobId: null,
        submitModelId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.submitInterfaceFieldList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.interfaceId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      // 打开窗口时查询文档信息
      this.fetchDocumentList(); 
      this.open = true;
      this.title = "添加文档接口信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.fetchDocumentList(); 
      const interfaceId = row.interfaceId || this.ids
      getInterface(interfaceId).then(response => {
        this.form = response.data;
        this.submitInterfaceFieldList = response.data.submitInterfaceFieldList;
        this.open = true;
        this.title = "修改文档接口信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.submitInterfaceFieldList = this.submitInterfaceFieldList;
          if (this.form.interfaceId != null) {
            updateInterface(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInterface(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const interfaceIds = row.interfaceId || this.ids;
      this.$modal.confirm('是否确认删除文档接口信息编号为"' + interfaceIds + '"的数据项？').then(function() {
        return delInterface(interfaceIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
	/** 接口字段序号 */
    rowSubmitInterfaceFieldIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 接口字段添加按钮操作 */
    handleAddSubmitInterfaceField() {
      let obj = {};
      obj.fieldCnName = "";
      obj.fieldEnName = "";
      obj.fieldType = "";
      obj.fieldLength = "";
      obj.fieldPrecision = "";
      obj.isRequired = "";
      obj.isPrimary = "";
      obj.fieldDesc = "";
      this.submitInterfaceFieldList.push(obj);
    },
    /** 接口字段删除按钮操作 */
    handleDeleteSubmitInterfaceField() {
      if (this.checkedSubmitInterfaceField.length == 0) {
        this.$modal.msgError("请先选择要删除的接口字段数据");
      } else {
        const submitInterfaceFieldList = this.submitInterfaceFieldList;
        const checkedSubmitInterfaceField = this.checkedSubmitInterfaceField;
        this.submitInterfaceFieldList = submitInterfaceFieldList.filter(function(item) {
          return checkedSubmitInterfaceField.indexOf(item.index) == -1
        });
      }
    },
    /** 接口字段导入按钮操作 */
    handleImportSubmitInterfaceField() {
      //先上传文件
      //将文件传给后端解析成json
      //将json数据赋值给table
    },
    /** 复选框选中数据 */
    handleSubmitInterfaceFieldSelectionChange(selection) {
      this.checkedSubmitInterfaceField = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('submit/interface/export', {
        ...this.queryParams
      }, `interface_${new Date().getTime()}.xlsx`)
    },
    disableFieldLength(fieldType) {
    return fieldType !== '1' && fieldType !== '4';
    },
    disableFieldPrecision(fieldType) {
      return fieldType !== '4';
    },
    isRequired(fieldType) {
      return fieldType === '1' || fieldType === '4';
    },
    // 获取文档列表
    fetchDocumentList() {
      // 调用接口获取文档列表数据
      listDocument().then(response => {
        this.documentList = response.rows;
      }).catch(error => {
        this.$modal.msgError("获取文档列表失败");
      });
      // 调用接口获取数据集列表数据
      listDataset().then(response => {
        this.datasetList = response.rows;
      }).catch(error => {
        this.$modal.msgError("获取数据集列表失败");
      });
      // 调用接口获取同步任务列表数据
      listJob().then(response => {
        this.jobList = response.rows;
      }).catch(error => {
        this.$modal.msgError("获取同步任务列表失败");
      });
    },
    // 时间配置json改变
    handleTimeConfigJsonChange(newTimeConfigJson) {
      // 将新的timeConfigJson赋值给form对象
      this.form.reportTimeConfig = newTimeConfigJson;
    }
  }
};
</script>
